package com.neusoft.neu24.nep.filter.globalfilter;

import com.neusoft.neu24.nep.utils.Auth4All;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    Auth4All auth4All;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        System.out.println("鉴权过滤器 filter");
        if (auth4All.pass()){
//            和普通的过滤器一样，继续执行
            return   chain.filter(exchange);
        }
        else {
            System.out.println("  STOP !!!!!!  - - - - -  -   -   ");
            log.info("请求参数中不包含custom参数, 请求非法, 拦截");
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            response.setStatusCode(HttpStatus.OK);
            byte[] bits =   ("{\n" +
                    "\"code\": 403,\n" +
                    "\"msg\": \"无权操作\",\n" +
                    "\t\"result\":null \n" +
                    "}").getBytes(StandardCharsets.UTF_8);

//            终止执行

            DataBuffer buffer = response.bufferFactory().wrap(bits);
            return response.writeWith(Mono.just(buffer));
//            return   exchange.getResponse().setComplete();
        }

    }

    @Override
    public int getOrder() {
//        数字越小，优先级越高
        return  Ordered.HIGHEST_PRECEDENCE +1  ;
    }
}
